<template>
  <div class="expanded">
    <div class="header">
      <div class="title">
        <div class="left">{{robotMode?'智能问答':(leftUser.nickname?leftUser.nickname:'正在分配客服')}}</div>
        <div v-if="imConnectionState!=-1" style="margin-right:10px;cursor: pointer;height:14px;display: inline-flex;align-items: flex-end;margin-left: 10px;">
          <div style="height: 30%;width: 3px;margin-right: 2px;" :style="{background:imConnectionState==0?'#333':'#FFF'}"></div>
          <div style="height: 60%;width: 4px;margin-right: 2px" :style="{background:imConnectionState==0?'#333':'#FFF'}"></div>
          <div style="height: 90%;width: 4px;margin-right: 2px" :style="{background:imConnectionState==0?'#333':'#FFF'}"></div>
        </div>
        <div class="change-mode" @click="$emit('changeMode')">
          <i class="el-icon-service" />{{robotMode?'转人工':'转智能'}}
        </div>
        <div class="call" v-if="!robotMode && leftUser.nickname" @click="startCall">
          <i class="el-icon-phone-outline" />
          视频通话
        </div>
      </div>
    </div>
    <div class="main">
      <div class="message">
        <div class="toolbar">
          <div class="toggle"></div>
          <div class="username">{{currentUser.name}}</div>
          <div class="more"></div>
        </div>
        <MsgBox ref="msgBox" class="msg-box" :left-user="leftUser" :right-user="currentUser"
                id-property="uid"/>
        <div class="send-box">
          <SendBox @send="sendChatMsg"/>
        </div>
      </div>
    </div>
    <div class="video-box" v-if="showCallPane">
      <video autoplay id="remote" class="large"></video>
      <div class="large" style="z-index: 5;display: flex;align-items: center;justify-content: center;color: #333333" v-if="!videoMeta.remote.ready">
        等待对方连接
      </div>
      <video autoplay id="local" class="thumb" muted></video>
      <div class="btn-group">
        <div class="close" @click="hangup">
          <div class="center-block"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {sendMessage} from "@/api/im";
import MsgBox from './components/message'
import SendBox from './components/send'

import {encodeChatMessage} from "@/modules/im/codec/encoder";
//监听消息
import {chatListeners,contactListeners} from "@/modules/im/command/listeners";
import {addListener,removeListener} from "@/modules/im/command/base";
import {getByQuestion} from "@/api/knowledge";
import {start, startCall, setListener, hangup} from "@/api/rtc/webrtc";

export default {
  name: "Chat",
  components:{
    MsgBox,
    SendBox
  },
  props:{
    leftUser:{
      type:Object,
      default:{}
    },
    robotMode:{
      type:Boolean,
      default: true
    }
  },
  data(){
    return {
      isExpand:false,
      lastHeight: 10000,
      showCallPane: false,
      videoMeta:{
        local:{
          audio:true
        },
        remote:{
          ready: false
        }
      }
    }
  },
  created() {
    let that = this
    addListener(chatListeners,'Chat',this.handleChatMsg)
    setListener({
      oniceconnectionstatechange: function (iceState) {
        switch (iceState) {
          case 'connected':
            that.$message.success('信道连接成功')
            that.videoMeta.remote.ready = true
            break
          case 'disconnected':
            that.$message.info('对方结束通话')
            that.showCallPane = false
            hangup()
            break
        }
      }
    })
  },
  mounted() {
    let that = this
    window.sendChatMsg = function(question) {
      that.sendChatMsg(question)
    }
    this.$nextTick(function (){
      window.onresize = function(){
        that.$refs.msgBox.scrollToBottom()
        window.scroll(0, 0)
      }
    })
  },
  methods:{
    handleChatMsg(obj){
      this.$refs.msgBox.handleNewMessage(obj)
    },
    handleChatMessages(arr) {
      this.$refs.msgBox.handleNewMessages(arr)
    },
    clearMsg() {
      this.$refs.msgBox.clearMsg()
    },
    startCall() {
      this.showCallPane = true
      this.$nextTick(function (){
        start(document.getElementById('local'),document.getElementById('remote')).then(isSuccess => {
          if(isSuccess) {
            startCall(this.leftUser.userId)
          }
        })
      })
    },
    hangup() {
      hangup()
      this.showCallPane = false
    },
    sendChatMsg(data) {
      // data = data.replace(/<\/?.+?>/g,"");
      this.handleChatMsg({sender:this.currentUser.visitorId,receiver:this.leftUser.userId,date:new Date().getTime(),type:'1',msg:data})
      //机器人模式
      if(this.robotMode) {
        getByQuestion(this.$store.state.tenantId,data).then(res => {
          if(res.code == 200) {
            this.handleRobotAnswer(data,res.data)
          }
        }).catch(() => {
          let data = [{
            answer:'网络连接可能出了问题，请稍后再尝试'
          }]
          this.handleRobotAnswer(null,data)
        })
        return
      }
      //人工客服模式
      let result = sendMessage(encodeChatMessage(this.leftUser.userId,this.leftUser.contactId,data))
      if(!result) {
        let data = [{
          answer:'网络连接可能出了问题，请稍后再尝试'
        }]
        this.handleRobotAnswer(null,data)
      }
    },
    handleRobotAnswer(question,answers) {
      let msg = ''
      if(answers.length == 0) {
        msg = '暂时找不到您想要的答案...'
      } else if(answers.length == 1 || answers[0].question == question) {
        msg = answers[0].answer
      } else {
        msg = '您是否为想找以下问题：\n'
        answers.forEach(function (item,index) {
          msg += (index+1) + '. ' + `<span style="cursor: pointer;color: #0091ff" onclick ="sendChatMsg('${item.question}')">${item.question}</span>` + '\n'
        })
      }
      this.handleChatMsg({sender:'robot',receiver:this.currentUser.visitorId,date:new Date().getTime(),type:'1',msg:msg})
    }
  },computed:{
    currentUser(){
      return this.$store.state.userInfo
    },
    imConnectionState() {
      return this.$store.state.imConnectionState
    }
  }
}
</script>

<style scoped lang="less">
  .expanded {
    background: #FAFAFA;
    transition: all .5s;
    transition-timing-function: ease-out;
    width: 100%;
    height: 100%;
    word-break: keep-all;
    opacity: 1;

    &.hidden{
      top: 100vh;
      bottom: 0;
      left: 100vw;
      right: 0;
      opacity: 0;
    }

    .header {
      display: flex;
      align-items: center;
      height: 40px;
      background: #409EFF;
      position: relative;
      color: #FFFFFF;
      .title {
        font-size: 16px;
        flex: 1;
        padding: 0 14px;
        line-height: 40px;
        display: flex;
        align-items: center;

        .left{
          flex: 1;
        }
        .change-mode {
          cursor: pointer;
          font-size: 14px;
          color: #F0F0F0;
          &:hover {
            text-decoration: underline;
          }
        }
        .name {
          margin-left: 10px;
          cursor: pointer;
        }
        .call {
          margin-left: 10px;
          cursor: pointer;
          font-size: 14px;
          color: #F0F0F0;
          &:hover {
            text-decoration: underline;
          }
        }
      }
      .close-btn {
        position: absolute;
        cursor: pointer;
        right: 0px;
        top: 0px;
        font-size: 20px;
        i {
          line-height: 40px;
          width: 40px;
          text-align: center;
        }
      }
    }

    @media(max-width: 670px) {
      .header {
        position: fixed;
        z-index: 2;
        top: 0;
        width: 100%;
      }
      .main {
        position: fixed;
        width: 100%;
        z-index: 1;
        top: 40px;
      }
    }

    .main {
      width: 100%;
      position: absolute;
      bottom: 0;
      top: 40px;

      .message {
        height: 100%;
        position: relative;
        .msg-box {
          width: 100%;
          top:0px;
          bottom: 160px;
          position: absolute;
        }
        .send-box {
          position: absolute;
          height: 160px;
          bottom: 0;
          width: 100%;
        }
        @media(max-width: 679px) {
          .msg-box {
            width: 100%;
            bottom: 50px;
          }
          .send-box {
            position: fixed;
            height: 50px;
          }
        }
      }
    }

    .video-box {
      position: absolute;
      bottom: 0;
      top: 0px;
      width: 100%;
      z-index: 10;
      background: #FFFFFF;

      .large {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 4;
        object-fit: cover;
      }
      .thumb {
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 150px;
        z-index: 5;
        object-fit: cover;
      }
      .btn-group {
        position: absolute;
        bottom: 50px;
        left: 0;
        right: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 8;
        .audio {
          border-radius: 50%;
          border: 1px solid #FFF;
          background: #FFF;
          color: #333333;
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          margin-right: 20px;
          cursor: pointer;
          box-shadow: 0px 0px 10px #8E8E8E;
          .line {
            width: 40px;
            height: 2px;
            background: #333333;
            transform: rotate(45px);
          }
        }
        .close {
          border-radius: 50%;
          width: 60px;
          height: 60px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          background: #FF3824;
          .center-block {
            background: #FFF;
            width: 15px;
            height: 15px;
          }
        }
        .track {
          border-radius: 50%;
          border: 1px solid #FFF;
          box-shadow: 0px 0px 10px #8E8E8E;
          background: #FFF;
          color: #333333;
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          margin-left: 20px;
          cursor: pointer;
        }
      }
      @media(max-width: 679px) {
        display: flex;
        flex-direction: column;
        .thumb {
          width: 150px;
          height: 200px;
        }
      }
    }
  }
</style>
